document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('todo-form');
    const input = document.getElementById('todo-input');
    const todoList = document.getElementById('todo-list');
    const searchInput = document.getElementById('search-input');
    let todos = [];

    function fetchTodos() {
        fetch('/api/todos')
            .then(response => response.json())
            .then(data => {
                todos = data;
                renderTodos();
            });
    }

    function renderTodos(todosToRender = todos) {
        todoList.innerHTML = '';
        todosToRender.forEach((todo, index) => {
            const li = document.createElement('li');
            li.className = `todo-item ${todo.completed ? 'completed' : ''} ${todo.status.toLowerCase()}`;
            li.innerHTML = `
                <input type="checkbox" ${todo.completed ? 'checked' : ''}>
                <span class="text">${todo.text}</span>
                <input type="text" class="edit-input" style="display: none;">
                <span class="time">${formatTime(todo)}</span>
                <span class="status">${todo.status}</span>
                <div class="actions">
                    <span class="edit">编辑</span>
                    <span class="delete">删除</span>
                    <select class="status-select">
                        <option value="TODO" ${todo.status === 'TODO' ? 'selected' : ''}>待办</option>
                        <option value="DOING" ${todo.status === 'DOING' ? 'selected' : ''}>进行中</option>
                        <option value="DONE" ${todo.status === 'DONE' ? 'selected' : ''}>完成</option>
                    </select>
                </div>
            `;
            
            const checkbox = li.querySelector('input[type="checkbox"]');
            checkbox.addEventListener('change', () => toggleTodo(index));
            
            const statusSelect = li.querySelector('.status-select');
            statusSelect.addEventListener('change', () => updateTodoStatus(index, statusSelect.value));
            
            todoList.appendChild(li);
        });
    }

    function formatTime(todo) {
        if (todo.completed && todo.completedAt) {
            const completedDate = new Date(todo.completedAt);
            const now = new Date();
            const diffDays = Math.floor((now - completedDate) / (1000 * 60 * 60 * 24));
            
            if (diffDays === 0) {
                return '今天完成';
            } else if (diffDays === 1) {
                return '昨天完成';
            } else {
                return `${diffDays}天前完成`;
            }
        }
        return '';
    }

    function addTodo(text) {
        fetch('/api/todos', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ text, completed: false, completedAt: null, status: 'TODO' }),
        })
        .then(response => response.json())
        .then(newTodo => {
            todos.push(newTodo);
            renderTodos();
        });
    }

    function toggleTodo(index) {
        const todo = todos[index];
        todo.completed = !todo.completed;
        todo.completedAt = todo.completed ? new Date().toISOString() : null;
        todo.status = todo.completed ? 'DONE' : 'TODO';

        fetch(`/api/todos/${todo.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(todo),
        })
        .then(() => {
            renderTodos();
        });
    }

    function editTodo(li, index) {
        const textSpan = li.querySelector('.text');
        const editInput = li.querySelector('.edit-input');
        const editBtn = li.querySelector('.edit');

        if (editBtn.textContent === '编辑') {
            textSpan.style.display = 'none';
            editInput.style.display = 'inline-block';
            editInput.value = todos[index].text;
            editInput.focus();
            editBtn.textContent = '保存';
        } else {
            const newText = editInput.value.trim();
            if (newText) {
                todos[index].text = newText;
                textSpan.textContent = newText;
                textSpan.style.display = 'inline';
                editInput.style.display = 'none';
                editBtn.textContent = '编辑';
                fetch(`/api/todos/${todos[index].id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(todos[index]),
                })
                .then(() => renderTodos());
            }
        }
    }

    function deleteTodo(index) {
        const todoId = todos[index].id;
        fetch(`/api/todos/${todoId}`, {
            method: 'DELETE',
        })
        .then(() => {
            todos.splice(index, 1);
            renderTodos();
        });
    }

    function searchTodos(query) {
        const filteredTodos = todos.filter(todo => 
            todo.text.toLowerCase().includes(query.toLowerCase())
        );
        renderTodos(filteredTodos);
    }

    function updateTodoStatus(index, newStatus) {
        const todo = todos[index];
        todo.status = newStatus;
        todo.completed = newStatus === 'DONE';
        todo.completedAt = todo.completed ? new Date().toISOString() : null;

        fetch(`/api/todos/${todo.id}/status`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(newStatus),
        })
        .then(response => response.json())
        .then(updatedTodo => {
            todos[index] = updatedTodo;
            renderTodos();
        });
    }

    form.addEventListener('submit', (e) => {
        e.preventDefault();
        const text = input.value.trim();
        if (text) {
            addTodo(text);
            input.value = '';
        }
    });

    searchInput.addEventListener('input', (e) => {
        searchTodos(e.target.value);
    });

    fetchTodos(); // 初始加载todos
});
